<template>
  <div class="auth">
    <!-- Form -->
    <el-button color="#626aef" @click="dialogFormVisible = true" style="float: left;margin: -100px" size="large">
      新建管理员
    </el-button>

    <el-dialog v-model="dialogFormVisible" title="新建管理员">
      <el-form :model="form">
        <el-form-item label="昵称：" :label-width="formLabelWidth">
          <el-input v-model="form.nickname" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户名：" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码：" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" type="password"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm(),dialogFormVisible=false">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-table :data="admins">
      <el-table-column prop="nickname" label="管理员昵称" width="300"/>
      <el-table-column prop="username" label="管理员用户名" width="300"/>
      <el-table-column label="操作" prop="id">
        <template #default="scope">
          <el-button type="danger" @click="deleteAdmin(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup>
import {getAdmins, addAdmin, deleteAdminByID} from "@/apis/auth";
import {ref, reactive} from "vue";
import {onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  nickname: '',
  username: '',
  password: ''
})


const confirm = async () => {
  const {nickname, username, password} = form
  await addAdmin({nickname, username, password}).then(res => {
    ElMessage({type: 'success', message: res.message})
  })
  getAllAdmin();
}


const admins = ref([])
const getAllAdmin = async () => {
  await getAdmins().then(res => {
    admins.value = res.data
  })
}

const deleteAdmin = (adminId) => {
  ElMessageBox.confirm(
      '你确定删除该信息吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        await deleteAdminByID(adminId).then(res => {
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getAllAdmin()
          } else {
            ElMessage({
              type: 'error',
              message: '你所删除的管理员不存在',
            })
          }
        })
      }).catch(() => {
    ElMessage({type: 'info', message: '操作取消'})
  })

}

onMounted(() => {
  getAllAdmin()
})
</script>
<style scoped>
.auth {
  width: 800px;
  margin: 100px auto;
}
</style>